<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Cache;
use App\Model\Class2Model;
use App\Model\StudentsModel;
use Illuminate\Support\Facades\DB;

class PublicController extends Controller
{
    //获得jwt
    static public function getJwt($type,$p){
        $usertype = $type;
        $jwtConfig = config('my.jwt');
        $header = array(
            'typ'=>'JWT',
            'alg'=>$jwtConfig['type']
        );
        $playload = array(
            'usertype'=>$usertype,
            'playload'=>$p,
            'logintime'=>time(),
            'validtime'=>time()+$jwtConfig['validity'],
        );

        $token = base64_encode(json_encode($header)).'.'.base64_encode(json_encode($playload));

        $token .= ('.'.hash_hmac($jwtConfig['type'],$token,$jwtConfig['key']));
        return $token;
    }

    //公开配置
    static public function config_GET(){
        $config = \config('my');
        return json_encode([
            //允许上传的字段
            'upload'=>[
                '学号'=>'stu_id',
                '姓名'=>'name',
                '大一班级'=>'class_base',
                '所学专业'=>'subject',
                'Python成绩'=>'score_python',
                'PHP成绩'=>'score_php',
            ],
            //约束，班级列表
            'uploaddtl'=>$config['upload'],
            //当前的综合成绩算法
            'scorerule'=>Cache::get('score_rule',$config['score_rule']),
            //允许搜索的字段
            'search'=>$config['search'],
            //大二专业
            'classlist'=>$config['class2'],
            //字段标题
            'field'=> $config['field']
        ]);
    }

        //获取当前班级容量，以及第一志愿填报数量
        public function peoplecount_GET(Request $requst)
        {
            //当前专业列表
            $subjectlist = array_keys(config('my.class2'));
            $subjectlist=DB::table('direction')->select('dir_name')->get();
            $arr=[];
            foreach ($subjectlist as $item){
                array_push($arr,$item->dir_name);
            }
            $subjectlist=$arr;
            //存储每个专业所要的最大容量,专业拥有的班级，班级个数
            $subject_info = [];
            foreach ($subjectlist as $k=>$y) {
                //查找专业班级数
                $res_class = Class2Model::where('subject', $y);
                //判断每个专业是否有对应的班级
                if (!$res_class->count()) {
                    die(json_encode(['error'=>'['.$y.']专业还没有分配班级']));
                }
                //每个班级的人数看做是相同的
                //班级个数
                $count = $res_class->count();
                //班级总容量和班级名称
                $capacity = $res_class->get()->reduce(function ($res, $item) {
                    return $res+=$item['maxcapacity'];
                });
                //获得当前第一志愿选择的数量
                $nowcount = StudentsModel::where('wish1',$y)->count();


                $subject_info[$y] = ['capacity'=>$capacity,'nowcount'=>$nowcount];
            }

            return json_encode($subject_info);
        }

}
